package com.dennytech.tac.utils.db;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.dennytech.tac.model.CFObject;
import com.dennytech.tac.utils.Log;

public abstract class DBHelper<T extends CFObject> {

	protected SQLiteDatabase db;
	protected String tableName;

	protected abstract String dbName();

	protected abstract File dbDir(Context c);

	protected DBHelper(Context c, String table) {
		this.tableName = table;
		try {
			db = createDataBase(c);
		} catch (IOException e) {
			Log.e("DBHelper", "createDataBase failed", e);
		}
	}

	protected SQLiteDatabase createDataBase(Context c) throws IOException {

		boolean dbExist = checkDataBase(c);

		if (!dbExist) {
			try {
				copyDataBase(c);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		File path = new File(dbDir(c), dbName());

		SQLiteDatabase db = null;
		try {
			db = SQLiteDatabase.openOrCreateDatabase(path, null);
		} catch (Exception e) {
			return null;
		}
		return db;
	}

	protected boolean checkDataBase(Context c) {
		File outFile = new File(dbDir(c), dbName());
		if (outFile.exists()) {
			return true;
		}
		return false;
	}

	protected void copyDataBase(Context c) throws IOException {
		InputStream myInput = c.getAssets().open(dbName());
		File outFile = new File(dbDir(c), dbName());
		OutputStream myOutput = new FileOutputStream(outFile);

		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}

		myOutput.flush();
		myOutput.close();
		myInput.close();
	}

	public void open() {
	}

	public synchronized void close() {
		if (db != null) {
			db.close();
		}
	}

	public abstract List<T> query();

	public void insert(T t) {
	}

	public int delete(T t) {
		return 0;
	}

	public int update(T t) {
		return -1;
	}
}
